<?php

namespace App\Listeners;

use App\Events\UserEvent;
use App\Library\User\PointManager;
use App\WeChat\WechatDefaultConfig;
use App\WechatMessages\ZPH\UserUpgradeMessage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class UserEventListener
{
    use WechatDefaultConfig;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  UserEvent $event
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function handle(UserEvent $event)
    {
        if ($event->type == 'login')
        {
            $event->user->logs()->create([
                'ip'=>request()->getClientIp(),
                'operate'=>'login',
                'created_at'=>time(),
                'src'=>request()->input('src', 'web')
            ]);
            //登录送积分

            $record = $event->user->pointRecords()
                ->where('from', 'login')->orderByDesc('id')
                ->first();
            if ($record)
            {
                if (@date('Ymd', $record->created_at) != date('Ymd'))
                {
                    PointManager::addPoints($event->user, setting('point_login'), 'login', '登录获得积分', 0);
                }
            } else {
                PointManager::addPoints($event->user, setting('point_login'), 'login', '登录获得积分', 0);
            }
        }

        //用户注册时触发
        if ($event->type == 'register')
        {
            //注册送积分
            PointManager::addPoints($event->user, setting('point_register'), 'register', '首次注册获得积分', 0);
        }

        //会员升级是出发
        if ($event->type == 'upgrade')
        {
            $connect = $event->user->connect;
            if ($connect)
            {
                $group = $event->user->group;
                $message = new UserUpgradeMessage();
                $message->setLavelName($group->title);
                $message->setUpgradeTime(date('Y-m-d H:i:s'));
                $message->setUrl(url('h5/user'));
                $event->user->sendTemplateMessage($message);
            }
        }

        //获得消费积分是触发
        if ($event->type == 'receivedbonuspoints')
        {
            //$wallet = $event->user->wallet;

        }
    }
}
